/*
 * 	Flan.Zeng 2011-2016	http://git.oschina.net/signup?inviter=flan
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.flan.stock.utils;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

/**
 * 异步加载并缓存图片的工具类
 * @author flan
 * @date   2015年11月8日
 */
public class SimpleAsyncImageLoader {
	
	private HashMap<String, SoftReference<Drawable>> imageCache;

	public SimpleAsyncImageLoader() {
		super();
		this.imageCache = new HashMap<String,SoftReference<Drawable>>();
	}
	
	public Drawable loadDrawable(final String imgUrl,final ImageCallback callback){
		
		if(imageCache.containsKey(imgUrl)){		//判断内存缓存中是否有该图片，有就直接返回图片
			SoftReference<Drawable> softReference = imageCache.get(imgUrl);
			Drawable drawable = softReference.get();
			if(drawable != null){
				return drawable;
			}
		}
		
		final Handler handler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				callback.imageLoaded(imgUrl, (Drawable)msg.obj);
			}
		};
		
		new Thread(){

			@Override
			public void run() {
				
				Drawable drawable = loadImageFromUrl(imgUrl);
				imageCache.put(imgUrl, new SoftReference<Drawable>(drawable));
				Message msg = handler.obtainMessage(0, drawable);
				handler.sendMessage(msg);
			}
			
		}.start();;
		
		return null;
	}
	
	/**
	 * 通过网络加载图片
	 * @param url	图片地址
	 * @return
	 */
	public static Drawable loadImageFromUrl(String url){
		
		URL m;
		InputStream is  = null;
		
		try {
			m = new URL(url);
			is = (InputStream) m.getContent();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		Drawable drawable = Drawable.createFromStream(is, "src");
		return drawable;
	}
	
	public interface ImageCallback{
		public void imageLoaded(String imgUrl,Drawable drawable);
	}
}
